package com.winqai.web.controller;

import com.fasterxml.jackson.annotation.JsonView;
import com.winqai.dto.User;
import com.winqai.dto.UserQueryCondition;
import com.winqai.exception.UserNotExistException;
import com.winqai.security.core.properties.SecurityProperties;
import com.winqai.security.core.social.AppSingUpUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

//import com.winqai.dto.User;
//import com.winqai.dto.UserQueryCondition;
//import com.winqai.exception.UserNotExistException;
//import io.swagger.annotations.ApiOperation;
//import io.swagger.annotations.ApiParam;
//import springfox.documentation.swagger2.annotations.EnableSwagger2;


@RestController
@RequestMapping("/user")
public class UserController {



    @Autowired//基于session
    private ProviderSignInUtils providerSignInUtils;

    @Autowired//基于redis
    private AppSingUpUtils appSingUpUtils;

    @Autowired
    private SecurityProperties securityProperties;

    @PostMapping("/regist")
    public void regist(User user, HttpServletRequest request) {

        //不管是注册用户还是绑定用户，都会拿到一个用户唯一标识。
        String userId = user.getUsername();
        if(request.getHeader("deviceId")== null){
            providerSignInUtils.doPostSignUp(userId, new ServletWebRequest(request));
        }else{
            appSingUpUtils.doPostSignUp(new ServletWebRequest(request),userId);
        }
    }
    /**
     * 获取验证后的用户认证信息
     * @param authentication
     * @return
     */
    @GetMapping("/me")
    public Object getCurrentUser(Authentication user , HttpServletRequest request) throws UnsupportedEncodingException {
        //return SecurityContextHolder.getContext().getAuthentication();

        //解析Jwt添加的自定义信息
        String header = request.getHeader("Authorization");
        String token = StringUtils.substringAfter(header,"bearer ");

        Claims claims = Jwts.parser().setSigningKey(securityProperties.getOauth2().getJwtSigningKey().getBytes("UTF-8"))
                .parseClaimsJws(token).getBody();

        String company = (String) claims.get("company");

        System.out.println("-============> " + company);
        return user;
    }


    //@RequestMapping(value = "/user",method = RequestMethod.GET)
    @GetMapping
    @JsonView(User.UserSimpleView.class)
    @ApiOperation(value = "用户查询服务")
    public List<User> query(UserQueryCondition condition, @PageableDefault(page = 2, size = 17, sort = "username,asc") Pageable pageable){
        System.out.println(ReflectionToStringBuilder.toString(condition, ToStringStyle.MULTI_LINE_STYLE));


        System.out.println(pageable.getPageSize());
        System.out.println(pageable.getPageNumber());
        System.out.println(pageable.getSort());

        List<User> users = new ArrayList<>();
        users.add(new User());
        users.add(new User());
        users.add(new User());
        return users;
    }

    //@RequestMapping(value = "/user/{id:\\d+}" ,method = RequestMethod.GET)
    @GetMapping("/{id:\\d+}")
    @JsonView(User.UserDetailView.class)
    public User getInfo( @ApiParam("用户id") @PathVariable String id) {

        System.out.println("进入getInfo服务");
        User user = new User();
        user.setUsername("tom");
        return user;
    }


    @GetMapping("/medetail")
    public Object getCurrentUserDetail(@AuthenticationPrincipal UserDetails user){
        return user;
    }
//
    @PutMapping("/{id:\\d+}")
    public User update(@Valid @RequestBody User user, BindingResult errors) {

        if (errors.hasErrors()){
            errors.getAllErrors().stream().forEach(error ->{
                FieldError fieldError = (FieldError) error;
                String message = fieldError.getField() + " "+ error.getDefaultMessage();
                System.out.println(message);
            });
            return null;
        }

        System.out.println(user.getId());
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        System.out.println(user.getBirthday());

        user.setId("1");
        return user;
    }

    @DeleteMapping("/{id:\\d+}")
    public void delete(@PathVariable String id) {
        System.out.println(id);
    }

    @PostMapping
   //@ApiOperation(value = "创建用户")
    public User create( @Valid @RequestBody User user ) {
//        if (errors.hasErrors()){
//            errors.getAllErrors().stream().forEach(error -> System.out.println(error.getDefaultMessage()));
//        }

        System.out.println(user.getId());
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        System.out.println(user.getBirthday());

        user.setId("1");

        return user;
    }

    @GetMapping("/error/{id:\\d+}")
    @JsonView(User.UserDetailView.class)
    public User getInfoError( @PathVariable String id) {
	//throw new RuntimeException("user not exist");
    throw new UserNotExistException(id);
//        System.out.println("进入getInfo服务");
//        User user = new User();
//        user.setUsername("tom");
//        return user;
    }
}
